package com.hyperdenton.HikCameraWrapper;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

@RequestMapping(value = "/camera")
@RestController
public class Controller {
    private HikCameraSdkWrapper hikCameraSdkWrapper = null;
    @Value("${camera.ip[0]}")
    String ip;
    @Value("${camera.port[0]}")
    String port;
    @Value("${camera.username[0]}")
    String username;
    @Value("${camera.password[0]}")
    String password;

    @PostMapping(path = "/login")
    public String loginCamera(@RequestParam("id") String id){
        //TODO: dynamically load config file (select camera config by id)
        try {
            if(hikCameraSdkWrapper == null)
                hikCameraSdkWrapper = new HikCameraSdkWrapper(ip, port, username, password);
            else
                return "already logged in!";
        } catch (Exception e) {
            return "login failed\n" + e;
        }
        return "login success";
    }

    @GetMapping(path = "/geturl")
    public String getUrl(){
        if(hikCameraSdkWrapper == null)
            return "login first please";
        String url = "";
        try {
            url = hikCameraSdkWrapper.getRtspUrl();
        } catch (Exception e) {
            return "fetch url failed\n" + e;
        }

        return url;
    }

    @GetMapping(path = "/logout")
    public String logOut(){
        if(hikCameraSdkWrapper == null)
            return "already logged out!";
        hikCameraSdkWrapper.close();
        hikCameraSdkWrapper = null;
        return "logout success";
    }

    @PostMapping(path = "/control")
    public String control(@RequestParam("direction") String dir,
                          @RequestParam("speed") Integer speed,
                          @RequestParam("duration") Integer duration){
        if(hikCameraSdkWrapper == null)
            return "login first please";
        try {
            hikCameraSdkWrapper.control(dir, speed, duration);
        } catch (Exception e) {
            return "control failed\n" + e;
        }
        return "control success";
    }

}
